package ink.metoo.gude.util

import ink.metoo.gude.handler.ApiException
import ink.metoo.gude.model.ApiBody
import ink.metoo.gude.model.ApiStatus

object ApiUtils {

    fun <T : Any> createBody(apiStatus: ApiStatus, record: T? = null) =
        ApiBody(code = apiStatus.code, message = apiStatus.message, record)

    fun Boolean.toBooleanBody(
        first: ApiStatus = ApiStatus.SUCCESS,
        second: ApiStatus = ApiStatus.FAIL
    ) = createBody<Boolean>(apiStatus = if (this) first else second)

    fun <T : Any> T?.toBody(apiStatus: ApiStatus = ApiStatus.SUCCESS) = createBody(apiStatus, this)

    fun <T : Any> success(record: T? = null) = createBody(apiStatus = ApiStatus.SUCCESS, record = record)

    fun <T : Any> run(block: () -> T) = success(block())

    fun ApiBody<*>.throwException(): Nothing =
        throw ApiException(apiStatus = ApiStatus.valueOf(code) ?: ApiStatus.FAIL, record)

}